// 凯利公式相关工具函数
export function calculateKellyRatio(winProb: number, winOdds: number): number {
  const b = winOdds - 1
  const p = winProb
  const q = 1 - winProb
  const kellyRatio = (b * p - q) / b
  return Math.max(0, kellyRatio)
}

export function calculateExpectedReturn(winProb: number, winOdds: number): number {
  return winProb * winOdds - (1 - winProb)
}

export function assessRisk(winProb: number, winOdds: number, kellyRatio: number): string {
  const expectedReturn = calculateExpectedReturn(winProb, winOdds)
  if (expectedReturn <= 0) return 'high'
  if (kellyRatio > 0.25) return 'high'
  if (kellyRatio > 0.1) return 'medium'
  return 'low'
}

export function calculateOptimalParams(winProb: number, winOdds: number) {
  const kellyRatio = calculateKellyRatio(winProb, winOdds)
  const expectedReturn = calculateExpectedReturn(winProb, winOdds)
  const recommendedStrategy = winProb > 0.5 ? 'anti-martingale' : 'martingale'
  let optimalInitialPosition: number
  if (expectedReturn <= 0 || kellyRatio <= 0) {
    optimalInitialPosition = 0.01
  } else {
    const safeKellyRatio = kellyRatio * 0.25
    optimalInitialPosition = Math.min(Math.max(safeKellyRatio, 0.005), 0.1)
  }
  let optimalIncreaseRatio: number
  let optimalDecreaseRatio: number
  let optimalPyramidLevels: number
  if (expectedReturn <= 0) {
    optimalIncreaseRatio = 1.0
    optimalDecreaseRatio = 1.0
    optimalPyramidLevels = 0
  } else {
    if (kellyRatio > 0.2) {
      optimalIncreaseRatio = 1.8 + Math.min(kellyRatio * 2, 1.2)
      optimalDecreaseRatio = Math.max(0.4, 0.8 - kellyRatio)
      optimalPyramidLevels = 3
    } else if (kellyRatio > 0.1) {
      optimalIncreaseRatio = 1.4 + kellyRatio * 2
      optimalDecreaseRatio = Math.max(0.6, 0.9 - kellyRatio)
      optimalPyramidLevels = 5
    } else {
      optimalIncreaseRatio = 1.1 + kellyRatio * 3
      optimalDecreaseRatio = Math.max(0.8, 0.95 - kellyRatio)
      optimalPyramidLevels = 8
    }
  }
  return {
    strategy: recommendedStrategy,
    initialPosition: Math.round(optimalInitialPosition * 10000) / 10000,
    increaseRatio: Math.round(optimalIncreaseRatio * 100) / 100,
    decreaseRatio: Math.round(optimalDecreaseRatio * 100) / 100,
    pyramidLevels: optimalPyramidLevels,
  }
}
